#!/bin/bash
set -Eeuo pipefail

#待扫描目录，多个目录按空格隔开，例如：“/aa /bb”
CONSTANT_DEFULAT_PATH="/sgeapp /home/${USER}"

DIR_CONF='conf/rps_dirs.conf'
FL_CONF='conf/file_list.conf'

if [[ $# -eq 1 ]] || [[ $# -eq 2 ]] && [[ "$1" = "-i" ]]
then
    MODIFY=1
else
    MODIFY=0
fi

if [[ $# -eq 2 ]] && [[ "$1" = "-i" ]] && [[ "$2" = "-b" ]]
then
    BACKUP=1
else
    BACKUP=0
fi


function init
{
    target_path=${CONSTANT_DEFULAT_PATH}
    regexp=""
    replace=""
    ignore='log|logs|.ssh|nohup.out|.bak|.swp|history|2021|__pycache__'
}

function get_directorys
{
    # 获取需要扫描的目录
    if [[ "${target_path}" != "${CONSTANT_DEFULAT_PATH}" ]]
    then
        echo ${target_path}
    else
        if [[ -s ${DIR_CONF} ]]
        then
            sed '/^#/d;/^$/d;s/#.*//' $DIR_CONF | sort | uniq
        else
            find ${target_path} -maxdepth 1 -type d -user ${USER}  
        fi
    fi
}

function get_file_list
{
    set +e -x
    egrep -rl "${regexp}" $(get_directorys) | grep -Ev "${ignore}"
    set -e +x
}

function update_file
{
    # $1 代表传递的文件列表
    set -x
    sed -nr "s/${regexp}/${replace}/gp" ${1}
    set +x
    if [[ ${MODIFY} -eq 1 ]]
    then
        if [[ ${BACKUP} -eq 1 ]]        
        then
            set -x
            sed -r -i.$(date +%Y%m%d%H%M%S)bak "s/${regexp}/${replace}/g" ${1}
            set +x
        else
            set -x
            sed -r  "s/${regexp}/${replace}/g" ${1}
            set +x
        fi
    fi
    
}


function work
{
    # 获取需要修改的文件列表
    echo "1.文件扫描......"
    if [[ -s ${FL_CONF} ]]
    then    
        file_list=$(sed '/^#/d;/^$/d;s/#.*//' ${FL_CONF} | sort | uniq)
    else
        file_list=$(get_file_list)
    fi

    
    if [ -n "${file_list}" ]
    then
        echo "**************待修改文件****************"
        echo " ${file_list}"
        echo " "
        echo "2.版本转换......"
        echo "***************修改文件*****************"
        update_file "${file_list}"
    else
        echo "   未扫描到可修改文件"
    fi
}

function main
{
    for f in $(ls conf/cvt*.sh)
    do
        # 获取新的配置,新的配置以变量的形式影响后面的运行
        init
        source ${f}
        echo "#######执行${f}的转换任务#######"
        work
    done
}

main
